<template>
  <el-container class="layout-container-demo" style="height: 100vh">
    <!-- 侧边栏 -->
    <el-aside :width="collapse ? '60px' : '200px'">
      <!-- 顶部 header -->
      <div class="aside-header">
        <el-avatar v-show="!collapse" size="32" src="src/assets/logo3.png" />
        <el-tooltip
            :content="collapse ? '展开导航' : '收起导航'"
            placement="right"
            popper-class="my-nav-tooltip"
            :hide-after="0"
        >
          <el-avatar
              size="32"
              src="src/assets/collapse-btn.png"
              class="avatar-pointer"
              @click="collapse = !collapse"
          />
        </el-tooltip>
      </div>

      <el-scrollbar>
        <el-menu
            :default-active="$route.path"
            router
            :collapse="collapse"
            :collapse-transition="false"
        >
          <el-menu-item index="/layout_user/creation">
            <el-icon><Cpu /></el-icon>
            <span v-show="!collapse">AI创作</span>
          </el-menu-item>
          <!-- 新增：创作中心 -->
          <el-menu-item index="/layout_user/creationSquare">
            <el-icon><MagicStick /></el-icon>
            <span v-show="!collapse">创作中心</span>
          </el-menu-item>  <!-- 新增：创作中心 -->

          <el-menu-item index="/layout_user/imageGen">
            <el-icon><Picture /></el-icon>
            <span v-show="!collapse">图片生成</span>
          </el-menu-item>
          <el-menu-item index="/layout_user/aiChat">
            <el-icon><ChatDotRound /></el-icon>
            <span v-show="!collapse">AI对话</span>
          </el-menu-item>
          <el-menu-item index="/layout_user/aiAnalysis">
            <el-icon><DataAnalysis /></el-icon>
            <span v-show="!collapse">AI解析</span>
          </el-menu-item>

          <el-menu-item index="/layout_user/aiSearch">
            <el-icon><Search /></el-icon>
            <span v-show="!collapse">AI查询</span>
          </el-menu-item>
          <el-menu-item index="/layout_user/creationlist">
            <el-icon><Document /></el-icon>
            <span v-show="!collapse">个人作品</span>
          </el-menu-item>
          <el-menu-item index="/layout_user/followList">
            <el-icon><Star /></el-icon>
            <span v-show="!collapse">我的关注</span>
          </el-menu-item>
        </el-menu>
      </el-scrollbar>

      <!-- 底部用户信息 -->
      <div class="user-info">
        <el-avatar
            size="32"
            :src="getAvatarUrl(store.cur_user?.avatar)"
            class="user-avatar"
            @click="dialogVisible = true"
        />
        <span v-show="!collapse" class="user-name">
        {{ store.cur_user?.nickName || store.cur_user?.loginName || '未知用户' }}
        </span>
      </div>

      <!-- 用户信息弹窗 -->
      <el-dialog v-model="dialogVisible" title="用户信息" width="380">
        <el-form label-width="90px">
          <el-form-item label="头像：">
            <div style="display: flex; align-items: center; gap: 12px;">
              <el-avatar
                  :size="60"
                  :src="getAvatarUrl(store.cur_user?.avatar)"
              />
              <el-upload
                  ref="uploadRef"
                  action="#"
                  :auto-upload="false"
                  :show-file-list="false"
                  :on-change="handleAvatarChange"
                  accept="image/*"
              >
                <el-button type="primary" size="small">更换头像</el-button>
              </el-upload>
            </div>
          </el-form-item>
          <el-form-item label="用户ID：">{{ store.cur_user?.id}}</el-form-item>
          <el-form-item label="登录名：">{{ store.cur_user?.loginName }}</el-form-item>
          <el-form-item label="昵称：">{{ store.cur_user?.nickName}}</el-form-item>
          <el-form-item label="邮箱：">{{ store.cur_user?.email}}</el-form-item>
          <el-form-item label="角色：">
            {{ store.cur_user?.role === 0 ? '普通用户' : store.cur_user?.role === 1 ? '管理员' : '未知' }}
          </el-form-item>
          <el-form-item label="积分：">{{ store.cur_user?. score }}</el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="dialogVisible = false">关 闭</el-button>
          <!-- 新增修改按钮 -->
          <el-button type="primary" @click="handleEditUserInfo">修改信息</el-button>
        </template>
      </el-dialog>
      <!-- 用户信息编辑弹窗 -->
      <el-dialog v-model="editDialogVisible" title="编辑用户信息" width="400">
        <el-form
            ref="editFormRef"
            :model="editForm"
            label-width="80px"
        >
          <el-form-item label="昵称" prop="nickName">
            <el-input v-model="editForm.nickName" placeholder="请输入昵称" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email" placeholder="请输入邮箱" />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button
              type="primary"
              @click="submitEditForm"
              :loading="editLoading"
          >
            确定
          </el-button>
        </template>
      </el-dialog>
    </el-aside>

    <!-- 右侧主体 -->
    <el-container>
      <el-header style="text-align: right; font-size: 12px">
        <div class="toolbar">
          <el-dropdown>
            <el-icon style="margin-right: 8px; margin-top: 1px"><Setting /></el-icon>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="logout">退出</el-dropdown-item>
                <el-dropdown-item @click="destroyAccount">注销</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <el-main style="flex: 1; display: flex; flex-direction: column">
        <router-view v-slot="{ Component }">
          <keep-alive :include="['AiSearch', 'CreationSquare', 'CreationList']">
            <component :is="Component" :key="$route.name" />
          </keep-alive>
        </router-view>
      </el-main>
    </el-container>
  </el-container>
</template>

<script lang="ts" setup>
import { ref,reactive } from 'vue'
import {
  ChatDotRound,
  Cpu,
  DataAnalysis,
  Document,
  MagicStick,
  Setting,
    Star,
} from '@element-plus/icons-vue'
import {userStore} from '../store/UserStore'
import {ElForm, ElMessage, ElMessageBox, type UploadProps, type UploadFile, type UploadInstance} from 'element-plus'
import axios from '../api/index'
import {useRouter} from "vue-router";
import {showSuccessToast} from "vant";

/* 折叠状态 */
const collapse = ref(false)
const store = userStore()
/* 弹窗开关 */
const dialogVisible = ref(false)
const editDialogVisible = ref(false)
/* 编辑表单相关 */
const editFormRef = ref<InstanceType<typeof ElForm>>()
const editLoading = ref(false)
// 上传组件引用
const uploadRef = ref<UploadInstance>()

// 添加路由实例
const router = useRouter()

// 获取头像URL的函数
const getAvatarUrl = (avatarName: string | null | undefined) => {
  if (!avatarName) {
    return 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png';
  }

  const baseURL = axios.defaults.baseURL || '';
  const cleanBaseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL;
  return `${cleanBaseURL}/img/avatar/${avatarName}`;
};

// 退出登录
const logout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 清除登录状态（根据实际项目需求调整）
    // localStorage.removeItem('token')

    // 跳转到登录页
    router.push('/login')

    showSuccessToast('已退出登录')
  }).catch(() => {
    // 用户取消操作
  })
}

// 注销账户
const destroyAccount = () => {
  ElMessageBox.confirm('确定要注销账户吗？此操作不可恢复！', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(() => {
    // 调用注销账户接口（根据实际项目需求调整）
    /*
    _axios.post('/user/destroy')
      .then(() => {
        ElMessage.success('账户已注销')
        router.push('/login')
      })
      .catch(() => {
        ElMessage.error('注销失败')
      })
    */
    // 暂时跳转到登录页
    router.push('/login')
    showSuccessToast('账户已注销')
  }).catch(() => {
    // 用户取消操作
  })
}

// 编辑表单数据
const editForm = reactive({
  nickName: '',
  email: ''
})

/* 处理头像上传 */
const handleAvatarChange: UploadProps['onChange'] = async (file: UploadFile) => {
  if (!file.raw) return

  // 检查文件类型
  if (!file.raw.type.startsWith('image/')) {
    ElMessage.error('只能上传图片文件')
    return
  }

  // 检查文件大小（限制为2MB）
  if (file.raw.size > 2 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过2MB')
    return
  }

  try {
    // 创建FormData对象
    const formData = new FormData()
    formData.append('avatar', file.raw)
    console.log('formData:', formData)

    // 调用上传头像接口
    const avatar=await axios.post('/user/avatar/update', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    // 使用后端返回的avatar信息更新store
    if (avatar) {
      store.cur_user.avatar = avatar
      // 更新 localStorage
      localStorage.setItem('user', JSON.stringify(store.cur_user))
    }

    ElMessage.success('头像上传成功')
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败: ' + (error.response?.data?.message || '请稍后重试'))
  }
}

/* 处理修改用户信息 */
const handleEditUserInfo = () => {
  // 关闭信息展示弹窗
  dialogVisible.value = false

  // 初始化编辑表单数据
  editForm.nickName = store.cur_user?.nickName || ''
  editForm.email = store.cur_user?.email || ''

  // 打开编辑弹窗
  editDialogVisible.value = true
}

/* 提交编辑表单 */
const submitEditForm = async () => {
  if (!editFormRef.value) return

  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      editLoading.value = true
      try {
        // 调用后端接口更新用户信息
        await axios.put('/user/update', {
          id: store.cur_user?.id,
          nickName: editForm.nickName,
          email: editForm.email
        })

        // 更新 store 中的用户信息
        if (store.cur_user) {
          store.cur_user.nickName = editForm.nickName
          store.cur_user.email = editForm.email
        }

        // 更新 localStorage
        localStorage.setItem('user', JSON.stringify(store.cur_user))

        ElMessage.success('用户信息更新成功')
        editDialogVisible.value = false
      } catch (error) {
        console.error('更新用户信息失败:', error)
        ElMessage.error('更新用户信息失败: ' + (error.response?.data?.message || '请稍后重试'))
      } finally {
        editLoading.value = false
      }
    }
  })
}
</script>

<style scoped>
/* ---------- 侧边栏整体 ---------- */
.el-aside {
  display: flex;
  flex-direction: column;
  background: #f3f5f6;
}

/* 顶部操作区 */
.aside-header {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 14px 0 16px;
  background: #f3f5f6;
  border-bottom: 1px solid #e4e7ed;
}

/* 折叠按钮 */
.avatar-pointer {
  --el-avatar-bg-color: transparent;
  cursor: pointer;
}
.avatar-pointer:hover {
  opacity: 0.8;
}

/* 菜单占满剩余高度 */
.el-scrollbar {
  flex: 1;
}

/* ---------- 底部用户信息 ---------- */
.user-info {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-top: 1px solid #e4e7ed;
}
.user-avatar {
  cursor: pointer;
}
.user-name {
  padding-left: 10px;
  white-space: nowrap;
}

/* ---------- 右侧头部 ---------- */
.el-header {
  position: relative;
  background-color: #f3f5f6;
  color: var(--el-text-color-primary);
}
.toolbar {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding-right: 20px;
}

/* ---------- 菜单样式 ---------- */
.el-menu {
  border-right: none;
  --el-menu-bg-color: #f3f5f6;
  --el-menu-hover-bg-color: #e9ecef;
  --el-menu-text-color: #303133;
  --el-menu-active-color: #409eff;
}
</style>